package com.cly.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.base.contants.CacheKeysConstants;
import com.cly.dto.MessageListDto;
import com.cly.entity.Message;
import com.cly.enums.MessageType;
import com.cly.mapper.MessageMapper;
import com.cly.result.JsonRequest;
import com.cly.result.exception.ServiceException;
import com.cly.result.exenum.RequestException;
import com.cly.service.IMessageService;
import com.cly.utils.WebSocketUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 消息记录业务层实现
 *
 * @author 春风能解释
 * <p>
 * 2024-06-05
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    /**
     * 注入消息记录数据层
     */
    private final MessageMapper messageMapper;

    /**
     * 批量删除消息记录信息
     *
     * @param ids 消息记录id列表
     * @return JSON
     */
    @Override
    @CacheEvict(value = CacheKeysConstants.MessageKeys.MESSAGE_LIST, allEntries = true)
    public JsonRequest<Integer> deleteMessages(List<Long> ids) {
        // 查询消息记录信息
        List<Message> messageList = messageMapper.selectBatchIds(ids);
        // 判断待删除的消息记录信息是否存在
        if (messageList.size() != ids.size()) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        int column = messageMapper.deleteByIds(ids);
        if (column < 1) {
            throw new ServiceException(RequestException.DELETE_ERROR);
        }
        return JsonRequest.success(column);
    }

    /**
     * 查看当前用户的最后一条消息记录
     *
     * @param userId 用户id
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.MessageKeys.MESSAGE_LIST, key = "#userId")
    public JsonRequest<List<Message>> lookMessageLast(Long userId) {
        return JsonRequest.success(messageMapper.lookMessageLast(userId));
    }

    /**
     * 发送消息
     *
     * @param message 消息体
     * @return JSON
     */
    @Override
    @CacheEvict(value = CacheKeysConstants.MessageKeys.MESSAGE_LIST, allEntries = true)
    public JsonRequest<Integer> sendMessage(Message message) {
        String sessionId = WebSocketUtils.sendMessageToUser(message);
        // 如果是发送消息，则将消息类型设置为文本消息
        if (!message.getType().equals(MessageType.SEND_MESSAGE.getValue())) {
            message.setIsText(false);
        }
        // 如果是视频通话相关的消息，则不记录到数据库中
        if (message.getType() > MessageType.SEND_MESSAGE.getValue() && message.getType() < MessageType.CLOSE_CALL.getValue()) {
            return JsonRequest.success(1);
        }
        Integer column = baseMapper.insert(message.setChannelId(sessionId));
        return JsonRequest.success(column);
    }

    /**
     * 查询消息记录(一对一)
     *
     * @param messageListDto 消息记录查询条件
     * @return JSON
     */
    @Override
    @Cacheable(value = CacheKeysConstants.MessageKeys.MESSAGE_LIST, key = "#root.args")
    public JsonRequest<List<Message>> lookMessage(MessageListDto messageListDto) {
        Page<Message> messagePage = page(new Page<>(messageListDto.getPage(), messageListDto.getSize()), Wrappers.lambdaQuery(Message.class)
                .eq(Message::getFrom, messageListDto.getMe())
                .eq(Message::getTo, messageListDto.getTo())
                .or(wrapper -> wrapper
                        .eq(Message::getFrom, messageListDto.getTo())
                        .eq(Message::getTo, messageListDto.getMe()))
                .orderByDesc(Message::getCreateTime)
        );
        List<Message> records = messagePage.getRecords();
        Collections.reverse(records);
        return JsonRequest.success(records, messagePage.getTotal());
    }

}